const $api = require('../../../../request/api.js').API;
import Dialog from '../../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import Toast from '../../../../miniprogram_npm/@vant/weapp/toast/toast';
import {
	deduplicateArray,
	deEmptyChildrenCascader,
	findPathDFS
} from '../../../../utils/hooks';
import {
	getAddress,
	getLatLng,
	initLocationPersmiss
} from '../../../../utils/util';

const app = getApp();
// var qqmapsdk;
Page({
	/**
	 * 页面的初始数据
	 */
	data: {
		variantIds: false, //判断是不是从提交订单页面来的
		beeperId: '',
		relationBeeperId: '',
		relationBeeperType: '',
		harvestId: '',
		// 中心经纬度
		latitude: 0,
		longitude: 0,
		// 目标记录点
		markers: [],
		address: '', // 位置名称
		detailAddress: '', // 这个是用来地址解析的
		province: '', //省
		city: '', //市
		district: '', //区
		street: '', //街道
		village: '', //小区，只有进来的
		villageId: '', //小区Id
		houseNumber: '', //门牌号
		houseNumberId: '', //门牌号id
		buildId: '', //栋id
		buildName: '', //栋名称
		floorName: '', //层name
		floorId: '', //层id
		unitName: '', //单元名称
		unitId: '', //单元id
		phone: '', //电话
		linkName: '', //联系人
		existVillage: false, //进来的时候呼叫器是否有小区
		showVillagePicker: false,
		villageList: [],
		showHouseNumber: false,
		residentAddress: {
			title: '',
			fieldNames: {
				text: 'name',
				value: 'id'
			},
			value: '',
			columns: [],
			originalColumns: [],
			show: false,
			multiple: false
		}
		// 进来的时候如果呼叫器有地址就解析保存起来
		// beeperLatitude:'',
		// beeperLongitude:'',
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		const {
			id,
			variantIds,
			relationBeeperId,
			harvestId
		} = options;
		// if(options.id){
		this.setData({
			beeperId: id,
			harvestId,
			variantIds, // 判断是不是从提交订单页面来的
			relationBeeperId: relationBeeperId == 'null' ? '' : relationBeeperId
		});

		// }

		// if(options.variantIds){
		//     // 判断是不是从提交订单页面来的
		//     this.setData({
		//         variantIds:options.variantIds
		//     })
		// }
		this.getBeeperInfo();
	},
	// 防止页面滚动，map组件里面放其它组件偶bug
	touchmove() {
		return;
	},
	// 输入
	inputValue(e) {
		let prop = e.currentTarget.dataset.prop;
		let value = e.detail.value;
		this.setData({
			[prop]: value
		});
	},
	// 获取小区列表
	getVillageList() {
		let params = {
			provinceName: this.data.province,
			cityName: this.data.city,
			areaName: this.data.district
			// streetNam:this.data.street
		};
		$api.getVillageList(params).then(res => {
			let data = res.data.data;
			if (!data || data.length == 0) {
				this.setData({
					villageList: [],
					village: '',
					villageId: ''
				});
				// Toast.fail("当前地址没有小区")
			} else {
				this.setData({
					villageList: data
				});
			}
		});
	},
	// 确认选择小区
	confirmVillage(e) {
		this.setData({
			village: e.detail.value.name,
			villageId: e.detail.value.id,
			showVillagePicker: false,
			houseNumber: '',
			houseNumberId: '',
			buildId: '',
			buildName: '',
			floorName: '',
			floorId: '',
			unitName: '',
			unitId: '',
			'residentAddress.value': ''
		});
		this.getResidentAddressList();
	},
	// 取消选择小区
	cancelVillage(e) {
		this.setData({
			showVillagePicker: false
		});
	},
	villagePickerPopup() {
		this.setData({
			showVillagePicker: true
		});
	},
	// 获取收货地址详情
	// getHarvestAddress(id){
	//     $api.getHarvestAddress({id:this.data.id}).then(res=>{
	//         let data = res.data.data
	//         this.data.markers[0]={
	//             latitude:data.latitude,
	//             longitude:data.longitude,
	//             iconPath:"../../../../static/position.png",
	//             width:35,
	//             height:35
	//         }
	//         this.setData({
	//             address:data.address,
	//             province:data.provinceName,
	//             city:data.cityName,
	//             district:data.areaName,
	//             street:data.street,
	//             houseNumber:data.houseNumber,
	//             latitude:data.latitude-0.0052,
	//             longitude:data.longitude,
	//             linkName:data.linkName,
	//             phone:data.phone,
	//             defaultStart:data.defaultStart,
	//             isEdit:true,
	//             markers:this.data.markers
	//         })
	//     })
	// },
	// 获取呼叫器地址详情
	getBeeperInfo() {
		if (this.data.harvestId) {
			$api.getHarvestAddress({
				id: this.data.harvestId
			}).then(res => {
				let data = res.data.data;
				this.setData({
					province: data.provinceName,
					city: data.cityName,
					district: data.areaName,
					street: data.streetName,
					village: data.villageName,
					villageId: data.villageId,
					houseNumber: data.houseNumber,
					houseNumberId: data.houseNumberId,
					buildId: data.buildId,
					buildName: data.buildName,
					floorName: data.floorName,
					floorId: data.floorId,
					unitName: data.unitName,
					unitId: data.unitId,
					existVillage: data.villageId ? true : false,
					linkName: data.linkName,
					phone: data.phone,
					latitude: data.latitude - 0.0052,
					longitude: data.longitude,
					address: data.address == '待补充' ? '' : data.address,
					'residentAddress.value': data.houseNumberId,
					relationBeeperType: data.relationBeeperType
				});

				if (data.provinceName) {
					let latitude = data.latitude;
					let longitude = data.longitude;
					if (latitude && longitude) {
						// 存在经纬度就直接赋予经纬度
						this.data.markers[0] = {
							latitude: latitude,
							longitude: longitude,
							iconPath: '../../static/position.png',
							width: 35,
							height: 35
						};
						this.setData({
							// beeperLatitude:latitude,
							// beeeperLongitude:longitude,
							// latitude:latitude-0.0052,
							// longitude:longitude,
							markers: this.data.markers
						});
					} else {
						// 不存在经纬度就地址解析出经纬度
						this.getLatLng();
					}
					this.getVillageList();
				} else {
					// 不存在地址就直接定位
					this.initLocationPersmiss();
				}
				this.getResidentAddressList();
			});
		} else {
			$api
				.getBeeperAddress({
					beeperId: this.data.beeperId
				})
				.then(res => {
					console.log(res, '地址详情');
					let data = res.data.data;
					this.setData({
						province: data.provinceName,
						city: data.cityName,
						district: data.areaName,
						street: data.streetName,
						village: data.villageName,
						villageId: data.villageId,
						houseNumber: data.houseNumber,
						houseNumberId: data.houseNumberId,
						buildId: data.buildId,
						buildName: data.buildName,
						floorName: data.floorName,
						floorId: data.floorId,
						unitName: data.unitName,
						unitId: data.unitId,
						existVillage: data.villageId ? true : false,
						linkName: data.linkName,
						phone: data.phone,
						latitude: data.latitude - 0.0052,
						longitude: data.longitude,
						address: data.address == '待补充' ? '' : data.address,
						'residentAddress.value': data.houseNumberId,
						relationBeeperType: data.relationBeeperType
					});

					if (data.provinceName) {
						let latitude = data.latitude;
						let longitude = data.longitude;
						if (latitude && longitude) {
							// 存在经纬度就直接赋予经纬度
							this.data.markers[0] = {
								latitude: latitude,
								longitude: longitude,
								iconPath: '../../static/position.png',
								width: 35,
								height: 35
							};
							this.setData({
								// beeperLatitude:latitude,
								// beeeperLongitude:longitude,
								// latitude:latitude-0.0052,
								// longitude:longitude,
								markers: this.data.markers
							});
						} else {
							// 不存在经纬度就地址解析出经纬度
							this.getLatLng();
						}
						this.getVillageList();
					} else {
						// 不存在地址就直接定位
						this.initLocationPersmiss();
					}
					this.getResidentAddressList();
				});
		}
	},
	// 选择地址
	selectAddress() {
		wx.chooseLocation({
			latitude: this.data.markers[0].latitude,
			longitude: this.data.markers[0].longitude,
			success: res => {
				console.log('选择地址', res);
				this.data.markers[0].longitude = res.longitude;
				this.data.markers[0].latitude = res.latitude;
				this.setData({
					detailAddress: res.address + res.name,
					address: res.name,
					latitude: res.latitude - 0.0052,
					longitude: res.longitude,
					markers: this.data.markers
				});
				// if(this.data.existAddress){
				//     // 如果进来的是时候是存在地址的那么就应该判断距离是不是过大
				//     this.getDistance()
				// }else{
				//     // 进来的时候如果不存在地址就可以随意选择地址，地址要解析成省市区街道
				this.getAddress();
				// }
			},
			fail: err => {
				console.log(err);
			}
		});
	},
	// 定位获取地址
	initLocationPersmiss() {
		initLocationPersmiss().then(res => {
			this.data.markers[0] = {
				latitude: res.location.lat,
				longitude: res.location.lng,
				iconPath: '../../static/position.png',
				width: 35,
				height: 35
			};
			this.setData({
				latitude: res.location.lat - 0.0052,
				longitude: res.location.lng,
				markers: this.data.markers
			});
		});
	},
	// 通过地址获取经纬度,地址解析
	getLatLng() {
		let params = this.data.province + this.data.city + this.data.district + this.data.village;
		getLatLng(params).then(res => {
			this.data.markers[0] = {
				latitude: res.location.lat,
				longitude: res.location.lng,
				iconPath: '../../../../static/position.png',
				width: 35,
				height: 35
			};
			this.setData({
				// beeperLatitude:res.location.lat,
				// beeeperLongitude:res.location.lng,
				latitude: res.location.lat - 0.0052,
				longitude: res.location.lng,
				markers: this.data.markers
			});
		});
	},
	// 通过经纬度获取地址,逆地址解析
	getAddress() {
		getAddress(this.data.markers[0].latitude, this.data.markers[0].longitude).then(res => {
			let province = res.address_component.province || '';
			let city = res.address_component.city || '';
			let district = res.address_component.district || '';
			let street = res.address_component.street || '';
			this.setData({
				province,
				city,
				district,
				street,
				// 地址解析之后需要清空小区
				villageId: '',
				village: '',
				houseNumber: '',
				houseNumberId: '',
				buildId: '',
				buildName: '',
				floorName: '',
				floorId: '',
				unitName: '',
				unitId: '',
				'residentAddress.value': '',
				'residentAddress.columns': []
			});
			this.getVillageList();
		});
	},
	// 检查输入是否正确
	checkSaveAddress() {
		if (!this.data.address) {
			Toast.fail('请完善详细地址');
			return false;
		}
		if (!this.data.houseNumber) {
			Toast.fail('请填写门牌号');
			return;
		}

		if (!this.data.linkName) {
			Toast.fail('请填写联系人');
			return false;
		}

		if (!this.data.phone) {
			Toast.fail('请填写联系电话');
			return;
		}
		if (!this.data.province) {
			Toast.fail('请选择地址');
			return;
		}
		if (this.data.villageList == 0 && this.data.existVillage) {
			// 有小区
			Toast.fail('请重新选择有小区的地址');
			return;
		}

		if (this.data.villageList.length > 0 && !this.data.village) {
			Toast.fail('请选择小区');
			return;
		}
		const regex = /^\d{1,12}$/;
		if (!regex.test(this.data.phone)) {
			Toast('联系电话格式不正确');
			return false;
		}

		return true;
	},
	// 保存地址
	async saveAddress() {
		if (!this.checkSaveAddress()) return;
		let params = {
			linkName: this.data.linkName,
			phone: this.data.phone,
			provinceName: this.data.province,
			cityName: this.data.city,
			areaName: this.data.district,
			streetName: this.data.street,
			villageId: this.data.villageId,
			villageName: this.data.village,
			address: this.data.address,
			houseNumber: this.data.houseNumber,
			houseNumberId: this.data.houseNumberId,
			buildId: this.data.buildId,
			buildName: this.data.buildName,
			floorName: this.data.floorName,
			floorId: this.data.floorId,
			unitName: this.data.unitName,
			unitId: this.data.unitId,
			beeperId: this.data.beeperId,
			longitude: this.data.markers[0].longitude,
			latitude: this.data.markers[0].latitude,
			relationBeeperId: this.data.relationBeeperId,
			harvestAddressId: this.data.harvestId,
			relationBeeperType: this.data.relationBeeperType
		};
		if (this.data.variantIds) {
			params.variantIds = this.data.variantIds;
			params.keepUp = 0;
		}
		let res = '';
		if (this.data.existVillage) {
			await Dialog.confirm({
				title: '提示',
				message: '请谨慎修改，数据无法恢复',
				confirmButtonText: '继续确认'
			});
			res = await $api.setBeeperAddress(params);
			res = res.data.data;
			if (res === 0) {
				await Dialog.confirm({
					title: '提示',
					message: '您的地址超出商家配送范围了哦',
					cancelButtonText: '调整地址',
					confirmButtonText: '仍然保存'
				});
				params.keepUp = 1;
				app.globalData.exceed = true;
				res = await $api.setBeeperAddress(params);
				res = res.data.data;
				app.globalData.harvestAddressId = res;
				// Toast.success({
				//     forbidClick:true,
				//     duration:1000,
				//     message:"设置成功",
				//     onClose:()=>{
				//         wx.navigateBack({
				//             delta:1
				//         })
				//     }
				// })
			}
			Toast.success({
				forbidClick: true,
				duration: 1000,
				message: '设置成功',
				onClose: () => {
					this.back(res, params.keepUp ? true : false);
				}
			});
		} else {
			res = await $api.setBeeperAddress(params);
			res = res.data.data;
			if (res === 0) {
				await Dialog.confirm({
					title: '提示',
					message: '您的地址超出商家配送范围了哦',
					cancelButtonText: '调整地址',
					confirmButtonText: '仍然保存'
				});
				params.keepUp = 1;
				app.globalData.exceed = true;
				res = await $api.setBeeperAddress(params);
				res = res.data.data;
				app.globalData.harvestAddressId = res.data.data;
			}
			Toast.success({
				forbidClick: true,
				duration: 1000,
				message: '设置成功',
				onClose: () => {
					this.back(res, params.keepUp ? true : false);
				}
			});
		}
	},
	back(data, exceed = false) {
		const {
			globalData
		} = app;
		if (this.data.variantIds && !exceed) {
			globalData.linkName = this.data.linkName;
			globalData.phone = this.data.phone;
			globalData.address = this.data.address;
			globalData.houseNumber = this.data.houseNumber;
			globalData.villageName = this.data.village;
			globalData.harvestAddressId = data;
		}
		// if(this.data.btnList){
		//   // 从首页下单来的，需要填写地址，那么就填写地址后直接跳到订单列表页面
		//   globalData.beeperOrderId = this.data.beeperId
		//   wx.navigateTo({
		//     url: '/pages/order/index',
		//   })
		// }else{
		wx.navigateBack({
			delta: 1
		});
		// }
	},

	// 获取地址列表
	async getResidentAddressList() {
		let res = await $api.getResidentAddressList({
			villageId: this.data.villageId
		});
		res = res.data.data || [];
		res = deEmptyChildrenCascader(res);
		// const address = findPathDFS(res, String(this.data.residentAddress.value));
		this.setData({
			'residentAddress.originalColumns': res,
			'residentAddress.columns': res
		});
	},

	async showHouseNumberPopup(e) {
		this.setData({
			'residentAddress.show': true
		});
	},
	confirmResidentAddress() {
		if (this.selectedOptions) {
			let selectArr = JSON.parse(JSON.stringify(this.selectedOptions));
			let houseNumber, houseNumberId, buildId, buildName, floorName, floorId, unitName, unitId;
			selectArr.forEach(item => {
				switch (item.levels) {
					case 1:
						buildId = item.id;
						buildName = item.name;
						break;
					case 2:
						unitName = item.name;
						unitId = item.id;
						break;
					case 3:
						floorName = item.name;
						floorId = item.id;
						break;
					case 4:
						houseNumber = item.name;
						houseNumberId = item.id;
						break;
				}
			});
			if (!buildId) {
				Toast.fail('请选择栋');
				return;
			}
			if (!unitId) {
				Toast.fail('请选择单元');
				return;
			}
			if (!floorId) {
				Toast.fail('请选择层');
				return;
			}
			if (!houseNumberId) {
				Toast.fail('请选择门牌号');
				return;
			}
			this.setData({
				buildId,
				buildName,
				unitName,
				unitId,
				floorName,
				floorId,
				houseNumber,
				houseNumberId,
				'residentAddress.value': houseNumberId
			});
		}
		this.selectedOptions = '';
		this.closeResidentAddress();
	},
	closeResidentAddress() {
		this.setData({
			'residentAddress.show': false,
			'residentAddress.value': this.data.houseNumberId
		});
	},

	/**
	 * cascader change
	 * @param e
	 */
	residentAddressChange(e) {
		const {
			selectedOptions
		} = e.detail;
		const {
			originalColumns,
			columns
		} = this.data.residentAddress;
		this.selectedOptions = selectedOptions;
		if (selectedOptions[0].children.length === 0 && selectedOptions[0].parentId === 0) {
			const _columns = columns;
			const index = columns.findIndex(item => item.id === selectedOptions[0].id);
			_columns[index].children = originalColumns.find(c => c.id === selectedOptions[0].id).children;
			setTimeout(() => {
				this.setData({
					'residentAddress.columns': _columns
				});
			}, 200);
		}
	},

	/**
	 * Cascader组件标签点击
	 * @param e
	 */
	handleCascaderTabClick(e) {
		const {
			columns,
			originalColumns
		} = this.data.residentAddress;
		const {
			tabIndex
		} = e.detail;
		const data = originalColumns.map(c => {
			return {
				id: c.id,
				levels: c.levels,
				name: c.name,
				parentId: c.parentId,
				children: []
			};
		});
		if (tabIndex === 0) {
			this.setData({
				'residentAddress.value': '',
				'residentAddress.columns': deduplicateArray(columns.concat(data))
			});
		}
	}
});